import { AxiosPromise, AxiosResponse, AxiosInstance } from 'axios';
import { Interceptors } from './interceptors';

// 请求配置
export class HttpServer {
  axios: AxiosInstance;
  static instance: HttpServer | null = null;

  // 获取axios实例
  constructor() {
    this.axios = new Interceptors().getInterceptors();
  }

  static getInstance() {
    if (!HttpServer.instance) {
      HttpServer.instance = new HttpServer();
      return HttpServer.instance;
    }
    return HttpServer.instance;
  }

  // 简单封装一下方法
  request(config: any): AxiosPromise {
    return new Promise((resolve, reject) => {
      this.axios(config)
        .then((res: AxiosResponse) => {
          resolve(res);
        })
        .catch((err: any) => {
          reject(err);
        });
    });
  }
}

const axiosInstance = HttpServer.getInstance();
export default axiosInstance.request.bind(axiosInstance);
